#include <windows.h>
#include "CUpdateCharPacket.h"
#include "MySQL/mysql.h"
#include "CDb.h"
#include "CLinkshell.h"


CUpdateCharPacket::CUpdateCharPacket(CChar *schar) {
	this->type = 0x37;
	this->size = 0x28;

	memset(data, 0, 80);

	unsigned long statusFoot = 0;
	for (int i = 0; i < 32; i++ ){
		if(schar->m_status[i] > 0x00FF) {
			data[i] = (unsigned char)(schar->m_status[i]-256);
			statusFoot ^= (0x00000001 << i);
		} else {
			data[i] = (unsigned char)(schar->m_status[i]);
		}
	}
	memcpy(data+0x4C-0x04, &statusFoot, 4);

	unsigned char red = 0x00;
	unsigned char green = 0x00;
	unsigned char blue = 0x00;
	CLinkshell * linkshell;
	linkshell = schar->getLinkshell();
	if(linkshell != NULL) {
		unsigned short lsColor = linkshell->getLsColor();
		red = (lsColor & 0xF);
		green = ((lsColor >> 4) & 0xF);
		blue = ((lsColor >> 8) & 0x0F);
	}
	// LSCOLOR (R G B)
	data[0x31-4] = (red * 16);
	data[0x32-4] = (green * 16);
	data[0x33-4] = (blue * 16);
	// END LS COLOR

	data[0x36-0x04] = 0x20;  //Ballista flag, bit 6, 0 = ballista, 1 = not ballista

	data[0x3C-0x04] = 0x20;
	data[0x3D-0x04] = 0xA0;
	data[0x3E-0x04] = 0x03;

	data[0x2C-0x04] = schar->m_speed;
	data[0x30-0x04] = schar->getAnimation();

	if(schar->getLinkshell() != NULL) {
		if(! (schar->h.nameFlag & 0x02)) {
			schar->h.nameFlag ^= 0x02;
		}
	} else {
		if((schar->h.nameFlag & 0x02)) {
			schar->h.nameFlag ^= 0x02;
		}
	}

	memcpy(data+0x24-0x04, &(schar->m_id), sizeof(schar->m_id));
	unsigned int status = ((schar->h.flags & 0xff000000) >> 5) + ((schar->h.flags & 0x000000ff) << 7);
	status |= (schar->getGender() * 0x8000);
	memcpy(data+0x28-0x04, &(status), sizeof(int));
	
    //Need to actually show the PT and anon flags
	if (schar->h.flags & 0x10) {
		data[0x28-0x04] ^= 0x10;
	}

	if (schar->h.flags & 0x20) {
	    data[0x28-0x04] ^= 0x20;
	}

    //Try to show chocobo
	if (schar->getAnimation() == 5) {
	    data[0x29-0x04] ^= 0x80;
	}

	data[0x2b-0x04] = schar->h.nameFlag;


	data[0x2A-0x04] = (unsigned char)(((float)schar->h.hp / (float)(schar->getMaxHp())) * 100);

	if(schar->m_pPet != NULL) {
		CBaseEntity * pet = (CBaseEntity*)schar->m_pPet;
		unsigned short targID = pet->getTargId();
		targID = targID << 3;
		memcpy(data+0x34-0x04, &targID, 2);
	}

	memcpy(data+0x44-0x04,&(schar->m_costume),sizeof(schar->m_costume));
	// 0x34 or equals Autogroup icon value
	Sleep(1);
}

CUpdateCharPacket::~CUpdateCharPacket() {
}